package com.xudow.app.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.activeshare.edu.ucenter.models.vo.ScheduleVO;
import com.xudow.app.R;
import com.xudow.app.ui.widget.ClassScheduleHScrollView;
import com.xudow.app.util.Lists;
import com.xudow.app.util.TimeUtils;
import com.xudow.app.util.Maps;
import com.xudow.app.util.WeekCalendar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;

/**
 * 课表Fragment
 *
 * @author lukecheng
 */
public class ClassScheduleFragment extends BaseFragment
        implements ClassScheduleHScrollView.ScrollChangeListener {

    /**
     * 一周7天
     */
    private static final int DAYS = 7;

    /**
     * 8:00到22:00 总共15个时间段
     */
    private static final int COURSE_SECTIONS = 15;

    /**
     * 从8点开始
     */
    private static int START_HOUR = 8;

    /**
     * 30分钟
     */
    private static int HALF_HOUR = 30;

    private int colors[] = {
            Color.rgb(0x7f, 0xc5, 0x24),
            Color.rgb(0xf0, 0x96, 0x09),
            Color.rgb(0x8c, 0xbf, 0x26),
            Color.rgb(0x00, 0xab, 0xa9),
            Color.rgb(0x99, 0x6c, 0x33),
            Color.rgb(0x3b, 0x92, 0xbc),
            Color.rgb(0xd5, 0x4d, 0x34),
            Color.rgb(0xcc, 0xcc, 0xcc)
    };

    private LinearLayout[] dayColumns = new LinearLayout[DAYS];
    private TextView[] dayTextViews = new TextView[DAYS];

    private ClassScheduleHScrollView scheduleScrollView;
    private HorizontalScrollView daysScrollView;

    private float courseSectionHeight;

    private List<ScheduleVO> courses;
    private int courseIndex;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        daysScrollView.scrollTo(l, t);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_class_schedule, container, false);

        courseSectionHeight = getResources().getDimension(R.dimen.class_schedule_hour_height);

        daysScrollView = (HorizontalScrollView) view.findViewById(R.id.days_view);
        daysScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        scheduleScrollView = (ClassScheduleHScrollView) view.findViewById(R.id.schedule);
        scheduleScrollView.setScrollChangeListener(this);

        dayColumns[0] = (LinearLayout) view.findViewById(R.id.day_column1);
        dayColumns[1] = (LinearLayout) view.findViewById(R.id.day_column2);
        dayColumns[2] = (LinearLayout) view.findViewById(R.id.day_column3);
        dayColumns[3] = (LinearLayout) view.findViewById(R.id.day_column4);
        dayColumns[4] = (LinearLayout) view.findViewById(R.id.day_column5);
        dayColumns[5] = (LinearLayout) view.findViewById(R.id.day_column6);
        dayColumns[6] = (LinearLayout) view.findViewById(R.id.day_column7);

        dayTextViews[0] = (TextView) view.findViewById(R.id.day1);
        dayTextViews[1] = (TextView) view.findViewById(R.id.day2);
        dayTextViews[2] = (TextView) view.findViewById(R.id.day3);
        dayTextViews[3] = (TextView) view.findViewById(R.id.day4);
        dayTextViews[4] = (TextView) view.findViewById(R.id.day5);
        dayTextViews[5] = (TextView) view.findViewById(R.id.day6);
        dayTextViews[6] = (TextView) view.findViewById(R.id.day7);

        this.initDays(new Date());

        return view;
    }

    /**
     * 初始化本周日期显示
     */
    private void initDays(Date dateInWeek) {
        String[] days = TimeUtils.getDaysOfWeek(dateInWeek);

        for (int i = 0; i < DAYS; i++) {
            dayTextViews[i].setText(days[i]);
        }
    }

    /**
     * 更新周一到周日日期显示
     */
    public void updateDayViews(int year, int month, int week) {
        WeekCalendar weekCalendar = new WeekCalendar(year, month, week);
        String[] days = weekCalendar.getWeekDaysWithMonth();

        for (int i = 0; i < DAYS; i++) {
            dayTextViews[i].setText(days[i]);
        }
    }

    /**
     * 设置课程的方法
     *
     * @param ll
     * @param title   课程名称
     * @param classes 节数
     * @param color   背景色
     * @param ci      courseIndex
     */
    void setClass(LinearLayout ll, String title, int classes, int color, int ci) {
        View view = LayoutInflater.from(this.getActivity()).inflate(R.layout.item_class_schedule, null);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ((int) courseSectionHeight / 2) * classes);
        params.setMargins(2, 0, 2, 0);
        view.setLayoutParams(params);

        view.setBackgroundColor(colors[color]);
        ((TextView) view.findViewById(R.id.title)).setText(title);
        ((TextView) view.findViewById(R.id.courseIndex)).setText("" + ci);

        view.setOnClickListener(new OnClickClassListener());

        ll.addView(view);
    }

    /**
     * 设置无课
     *
     * @param ll
     * @param classes 无课的节数（长度）
     */
    void setNoClass(LinearLayout ll, int classes) {
        View v=View.inflate(this.getMyAct(),R.layout.class_schedul_item,null);
        TextView blank = (TextView)v.findViewById(R.id.tv);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                (int) (getResources().getDimension(R.dimen.class_schedule_hour_height) / 2));

        v.setLayoutParams(params);

        if (classes % 2 == 1) {
            blank.setBackgroundColor(getResources().getColor(R.color.class_schedule_item));
            //blank.setBackgroundResource(R.drawable.grey_border_bottom);
        } else {
            blank.setBackgroundColor(getResources().getColor(R.color.app_background));
        }

        ll.addView(v);
    }


    //点击课程的监听器
    class OnClickClassListener implements View.OnClickListener {
        public void onClick(View v) {
            String index = ((TextView) v.findViewById(R.id.courseIndex)).getText().toString();
            int indexNum = Integer.parseInt(index);

            ScheduleVO scheduleVO = courses.get(indexNum);

            if (null != onScheduleViewClickListener) {
                onScheduleViewClickListener.onScheduleClick(scheduleVO);
            }
        }
    }

    /**
     * 设置课表信息
     */
    public void setSchedules(List<ScheduleVO> schedules) {
        courseIndex = 0;
        courses = new ArrayList<ScheduleVO>();

        /**
         * Map<Day,  List<ScheduleVO>>
         * 一天有那些课
         */
        Map<Integer, List<ScheduleVO>> scheduleMap = Maps.newHashMap();

        for (ScheduleVO sv : schedules) {
            int dayInWeek = TimeUtils.dayForWeek(sv.getDate()) - 1;

            if (scheduleMap.get(dayInWeek) == null) {
                List<ScheduleVO> vos = new ArrayList<ScheduleVO>();
                vos.add(sv);
                scheduleMap.put(dayInWeek, vos);
            } else {
                scheduleMap.get(dayInWeek).add(sv);
            }

        }
        for (int i = 0; i < DAYS; i++) {
            dayColumns[i].removeAllViews();
        }

        courseIndex = 0;

        for (int i = 0; i < DAYS; i++) {
            List<ScheduleVO> daySchedules = scheduleMap.get(i);

            if (null == daySchedules || daySchedules.size() <= 0) {
                //整天都没课
                for (int j = 0; j < COURSE_SECTIONS * 2; j++) {
                    setNoClass(dayColumns[i], j);
                }
            } else {
                int[] regions = parseSchedule(daySchedules);
                int mask = 1;

                for (int j = 0; j < COURSE_SECTIONS * 2; ) {
                    if (0 == regions[j]) {
                        setNoClass(dayColumns[i], j);
                        j++;
                    } else {
                        int start = j;
                        int end = j;

                        while (regions[j] == mask) {
                            j++;
                        }

                        end = j;

                        ScheduleVO course = courses.get(courseIndex);
                        setClass(dayColumns[i], course.getScheduleInfo(), (end - start), 0, courseIndex);

                        courseIndex++;

                        mask++;
                    }
                }
            }
        }
    }

    /**
     * 解析一天的课程
     *
     * @param schedules
     * @return
     */
    private int[] parseSchedule(List<ScheduleVO> schedules) {
        //移除重叠
       // List<ScheduleVO> schedules = removeOverlapped(scheduleList);

        Collections.sort(schedules, new Comparator<ScheduleVO>() {
            @Override
            public int compare(ScheduleVO lhs, ScheduleVO rhs) {
                String[] lhsTimes = lhs.getTimes().split("-")[0].split(":");
                String[] rhsTimes = rhs.getTimes().split("-")[0].split(":");

                int lhsHour = Integer.parseInt(lhsTimes[0]);
                int lhsMin = Integer.parseInt(lhsTimes[1]);

                int rhsHour = Integer.parseInt(rhsTimes[0]);
                int rhsMin = Integer.parseInt(rhsTimes[1]);

                int ret = 0;
                if (lhsHour > rhsHour) {
                    ret = 1;
                } else if (lhsHour == rhsHour) {
                    if (lhsMin > rhsMin) {
                        ret = 1;
                    } else if (lhsMin == rhsMin) {
                        ret = 0;
                    } else if (lhsMin < rhsMin) {
                        ret = -1;
                    }
                } else if (lhsHour < rhsHour) {
                    ret = -1;
                }

                return ret;
            }
        });

        int[] regions = new int[COURSE_SECTIONS * 2];
        int mask = 1;

        for (int i = 0; i < COURSE_SECTIONS * 2; i++) {
            regions[i] = 0;
        }

        for (ScheduleVO vo : schedules) {
            courses.add(vo);

            String[] times = vo.getTimes().split("-");
            String[] startTime = times[0].split(":");
            String[] endTime = times[1].split(":");

            int startTimeHour = Integer.parseInt(startTime[0]);
            int startTimeMinute = Integer.parseInt(startTime[1]);

            int endTimeHour = Integer.parseInt(endTime[0]);
            int endTimeMinute = Integer.parseInt(endTime[1]);

            int span = (endTimeHour - startTimeHour) * 2;
            int start = (startTimeHour - START_HOUR) * 2;

            int i = start;

            if (startTimeMinute > 0) {
                if (startTimeMinute < HALF_HOUR) {
                    //(i % 2) == 1 标识不是整点
                    if (start > 0 && ((i % 2) == 1)) {
                        regions[i - 1] = mask;
                    } else {
                        regions[i] = mask;
                    }
                } else {
                    regions[i] = 0;
                    i++;
                }
            }

            int end = span + start;
            Log.e("parseSchedule","start:"+start+"---"+"end:"+end+"span"+span);
            for (; i < end; i++) {
                regions[i] = mask;
            }

            if (endTimeMinute < HALF_HOUR && endTimeMinute != 0) {
                regions[i] = mask;
            }

            if (endTimeMinute == HALF_HOUR && endTimeMinute != 0) {
                regions[i] = mask;
            }

            if (endTimeMinute > HALF_HOUR && endTimeMinute != 0) {
                regions[i] = mask;

                if (end < COURSE_SECTIONS * 2) {
                    regions[++i] = mask;
                }
            }

            mask++;
        }
        return regions;
    }

    /**
     * 去掉时间重叠的课程
     *
     * @param schedules
     * @return
     */
    private List<ScheduleVO> removeOverlapped(List<ScheduleVO> schedules) {
        List<ScheduleVO> vos = Lists.newArrayList();

        for (ScheduleVO vo : schedules) {
            boolean overlapped = false;

            for (ScheduleVO tmp : vos) {
                String[] lhsTimes = tmp.getTimes().split("-")[0].split(":");
                String[] rhsTimes = vo.getTimes().split("-")[0].split(":");

                String[] lhsTimesEnd = tmp.getTimes().split("-")[1].split(":");
                String[] rhsTimesEnd = vo.getTimes().split("-")[1].split(":");

                int lhsHour = Integer.parseInt(lhsTimes[0]);
                int rhsHour = Integer.parseInt(rhsTimes[0]);

                int lhsHourEnd = Integer.parseInt(lhsTimesEnd[0]);
                int rhsHourEnd = Integer.parseInt(rhsTimesEnd[0]);

                if ((rhsHour >= lhsHour && rhsHour <= lhsHourEnd)
                        || (rhsHourEnd >= lhsHour && rhsHourEnd <= lhsHourEnd)) {
                    overlapped = true;
                    break;
                }
            }

            if (!overlapped) {
                vos.add(vo);
            }
        }

        return vos;
    }

    /**
     * 点击课程Listener
     */
    public interface OnScheduleViewClickListener {
        void onScheduleClick(ScheduleVO vo);
    }

    private OnScheduleViewClickListener onScheduleViewClickListener;

    public void setOnScheduleViewClickListener(OnScheduleViewClickListener listener) {
        this.onScheduleViewClickListener = listener;
    }
}